qui(
    function (require, exports, module) {
        Director.Player = (function () {
            var params = {};
            params.scale = "noscale";
            params.salign = "tl";
            params.wmode = "transparent";
            params.swliveconnect = "true";
            params.allowfullscreen = "true";
            params.allowscriptaccess = "always";
            params.allownetworking = "all";
            params.bgcolor = "#000000";
            var player = {};
            player.swf = "http://www.iqiyi.com/player/20130702143439/expressInstall.swf";
            player.version = "10.0.0";
            player.liveUrl = "/epg/swfs/broadcastingLivePlayer.swf";
            player.microUrl = "/epg/swfs/SignalPlayer.swf";
            player.effectUrl = "/epg/swfs/SignalPreview.swf";

            var manager = {
                oldId: 0,
                newId: 0
            };

            var recordResource = { };
            var recordBackup = { };

            var delayNotifyMap = {};

            var recordEffectImage = {},
                recordEffectSubtitle = {},
                recordEffectAnimation = {},
                recordEffectAudio = {};

            var effectFlashId = 'effectFlv';

            // 左侧播放器
            function initLeftPlayer(streamUrl) {
                var attributes = {};
                attributes.id = "flashOutPutPreview"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = "flv"

                if(checkFlash()) {
                    swfobject.embedSWF(player.liveUrl, "flv", "100%", "395", player.version, player.swf, flashvars, params, attributes, flashCallBack);
                }else{
                    noFlashTip("flv");
                }
            }

            function initEffectPlayer(streamUrl) {
                var attributes = {};
                attributes.id = "effectFlv"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = effectFlashId,
                flashvars.videoWidth = '640';
                flashvars.videoHeight = '360';
                flashvars.rtmpUrl = streamUrl;
                var effectParams = $.extend(true,{},params) ;
                effectParams.wmode = "opaque";
                swfobject.embedSWF(player.effectUrl, "effectFlv", "100%", "395", player.version, player.swf, flashvars, effectParams, attributes, flashCallBack);
            }

            function initPreviewPlayer(streamUrl) {
                var _attributes = {};
                _attributes.id = "flashOutput"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
                flashvars.flashId = "flv_preview"
                //  flashvars =  {url:"rtmp://101.227.188.120:1935/liveshow/rtsh61_ogkrxbsn",type:"rtmp"}
                swfobject.embedSWF(player.liveUrl, "flv_preview", "100%", "270", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
            }


            function initFlvPreviewPlayer(streamUrl) {
                var _attributes = {};
                _attributes.id = "flv_preview_foreground"
                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl)
                flashvars.flashId = "flv_preview_foreground"
                //  flashvars =  {url:"rtmp://101.227.188.120:1935/liveshow/rtsh61_ogkrxbsn",type:"rtmp"}
                swfobject.embedSWF(player.liveUrl, "flv_preview_foreground", "410", "255", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
            }

            function makeUpFlashvarsByStreamUrl(streamUrl){
                var flashvars = {url: streamUrl};
                if (streamUrl.startsWith("http")) {
                    flashvars.type = "http";
                } else if (streamUrl.startsWith("rtmp")) {
                    flashvars.type = "rtmp";
                }
                return flashvars;
            }

            function flashCallBack(data) {
                console.log(" flashCallBack :" + JSON.stringify(data))
            }


            // flash 交互
            // 方法名：changeSource
            //  参数：id(Int)    当前正在播放的信号源对应的flash player编号
            //   // 缩略直播视频预览播放器
            function initMicroPlayer(element) {
                //wait todo
                var _attributes = {};
                var flashvars = {};
                _attributes.id = "flashPlayer" + element.id
                flashvars = {resourceId: element.id,isBackup:element.isBackup}; // isBackup  0：是普通资源 ，1：灾备资源
                var needQueryRtmp = false;
                switch (element.signalType) {
                    case 0:
                        if (element.signalUrl == null || element.signalUrl.length == 0) {
                            needQueryRtmp = true;
                        }
                        flashvars.picUrl = element.snapshotUrl;
                        break;
                    case 1:
                        flashvars.objectId = Number(element.signalLegoId);
                        flashvars.percentApiUrl = element.productStatusUrl;
                        flashvars.cyclicNum = element.playCounts;
                        break;
                    case 2:
                        flashvars.rtmpUrl = element.signalPreviewUrl;
                        flashvars.picUrl = element.snapshotUrl;
                        break;
                }
                swfobject.embedSWF(player.microUrl, "flash" + element.id, "100%", "100%", player.version, player.swf, flashvars, params, _attributes, flashCallBack);
                if (needQueryRtmp) {
                    getRtmpStreamByResource(element)
                }
            }

            function getRtmpStreamByResource(element) {
                var qipuId = Number(element.signalId)
                var options = {
                    url: Director.urlConfig.queryRtmpUrl,
                    dataType: 'json',
                    data: {qipuId: qipuId},
                    type: "get",
                    success: function (data) {
                        if (data != null && data.code == "A00000") {
                            if (data.data.input_url.length > 0) {
                                sendToFlash("flashPlayer" + element.id, {type: "changeRtmp", data:{rtmpUrl: data.data.input_url}});
                            }
                            console.log("getRtmpStreamByResource suc:" + JSON.stringify(data))
                        }
                    },
                    error: function (data) {
                        console.error("getRtmpStreamByResource fail")
                    }
                }
                $.ajax(options)
            }

            function queryRtmpByResourceId(resourceId) {
                var element = recordResource["flash" + resourceId];
                if (element != null && element.signalType) {
                    getRtmpStreamByResource(element);
                }
            }
            function checkResourceSwitch(resourceId ,time, playCounts){
                var element = recordResource["flash" + resourceId];
                if(element == null ){
                    console.warn("element is null :"+resourceId)
                    return ;
                }
                if(element.isBackup == 1){
                    console.log("灾备资源不处理:"+JSON.stringify(element));
                    return ;
                }
                Director.Util.doResourceSwitch(resourceId,time, playCounts);
            }

//
            function sendToFlash(flashId, obj , needDelay) {
                if(!needDelay){
                    var target = thisMovie(flashId);
                    if (target != null) {
                        console.log("[sendToFlash]"+flashId + ":" + JSON.stringify(obj));
                        try {
                            target.notifyFlash(JSON.stringify(obj));
                        } catch (e) {
                            console.log(e);
                            needDelay = true;
                        }
                    }
                }
                if( needDelay ){
                    if (!delayNotifyMap.hasOwnProperty(flashId)) {
                        delayNotifyMap[flashId] = [];
                    }
                    delayNotifyMap[flashId].push(obj);
                }
            }

            function initPlayer() {
                var self = this;
                var entity = Director.Util.getEntity();

                //entity.outputPreviewUrl = 'rtmp://10.121.86.127/live/test_360p,rtmp://10.121.86.127/live/test_360p_1';

                initLeftPlayer(getOutputPreviewUrl(entity.outputPreviewUrl));
                // initPreviewPlayer(entity.outputUrl);

                var effectPreviewUrl = getEffectPreviewUrl(entity.outputPreviewUrl);
                if(effectPreviewUrl != "") {
                    initEffectPlayer(effectPreviewUrl);
                }else{
                    console.log("not preview url for effect player");
                }
            }

            function getOutputPreviewUrl(url) {
                var urls = new Array();
                urls = url.split(",");
                return urls[0];
            }

            function getEffectPreviewUrl(url) {
                var urls = new Array();
                urls = url.split(",");
                if(urls.length > 1) {
                    return urls[1]
                }else{
                    return "";
                }
            }

            function createPreview(){
                var entity = Director.Util.getEntity();
                initPreviewPlayer(entity.outputUrl);
            }

            function createFlvPreview() {
                var entity = Director.Util.getEntity();
                initFlvPreviewPlayer(entity.outputUrl);
            }

            function notifyHandler(event) {
                switch (event.type) {
                    case "startPlay":
                        console.log("startPlay:" + JSON.stringify(event));
                        checkResourceSwitch( event.data.resourceId,event.data.time == null ? 0 : event.data.time, event.data.cyclicNum);

                        break;
                    case "queryRtmp":
                        queryRtmpByResourceId(event.data.resourceId);
                        break;
                    case "initComplete":
                        console.log("initComplete : " + JSON.stringify(event))
                        doDelayEvent("flashPlayer" + event.data.resourceId);
                        break;
                    case "initPreviewComplete":
                        console.log("initPreviewComplete : " + JSON.stringify(event))
                        if (event.data.flashId == "flv_preview") {
                            doDelayEvent(event.data.flashId);
                        }
                        break;
                    case "initEffectPreviewComplete":
                        console.log("initEffectPreviewComplete: " + JSON.stringify(event));
                        break;
                    case "effectPreviewData":
                        console.log("effectPreviewEditData: " + JSON.stringify(event));
                        Director.Util.submitPreviewAllEffects(event['data']);
                        //Director.Util.batchEditEffect(event['data']);
                        //Director.Util.batchEditEffect(event['data'], function(data) {
                        //    Director.Util.batchStopPreview(data, function(data) {
                        //        Director.Util.batchStartPreview(data, function(data) {
                        //        });
                        //    })
                        //});

                        break;
                    //case "effectPlayData":
                    //    console.log("effectPlayEditData");
                    //    break;
                    case "effectDelete":
                        console.log("effectDelete: " + JSON.stringify(event));
                        Director.Util.notifyStopPreviewEffectByFlash(event['data']);
                        break;
                    case "commentaryPlay":
                        console.log("commentaryPlay: " + JSON.stringify(event));
                        Director.Commentary.playCommentary(event['data']);
                        break;
                    case "commentaryStopPlay":
                        console.log("commentaryStopPlay: " + JSON.stringify(event));
                        Director.Commentary.stopCommentary(event['data']);
                        break;
                    case "commentaryChangeVolumn":
                        console.log("commentaryChangeVolumn : " + JSON.stringify(event));
                        Director.Commentary.changeCommentaryVolumn(event['data']);
                        break;
                    case "commentaryDelete":
                        console.log("commentaryDelete: " + JSON.stringify(event));
                        Director.Commentary.delCommentary(event['data']);
					case "setCyclicNum":
                        console.log("setCyclicNum: " + JSON.stringify(event));
                        Director.Util.notifySetResourcePlayCounts(event['data']);
                        break;
                    case "endPlay":
                        console.log("endPlay: " + JSON.stringify(event));
                        changeFlash();
                        break;
                    case "changeCyclic":
                        console.log("changeCyclic: " + JSON.stringify(event));

                    default :
                        break;
                }
            }

            function doDelayEvent(flashId) {
                if (delayNotifyMap.hasOwnProperty(flashId)) {
                    var waitTodoArr = delayNotifyMap[flashId];
                    if(waitTodoArr.length > 0){
                        delayNotifyMap[flashId] = [];
                        console.log("doDelayEvent start ;"+flashId);
                        $.each(waitTodoArr, function (i, eventObj) {
                            sendToFlash(flashId, eventObj);
                        })
                        console.log("doDelayEvent end ;"+flashId + ";"+JSON.stringify(  delayNotifyMap[flashId]  ));
                    }
                }
            }

            function recordDiff(obj1, obj2) {
                obj1.diff = {hasChange: false};
                if (obj1.signalName != obj2.signalName) {
                    obj1.signalName = obj2.signalName;
                    obj1.diff.hasChange = true;
                    obj1.diff.signalName = obj2.signalName;
                }
                if (obj1.isDefaultBackup != obj2.isDefaultBackup) {
                    obj1.isDefaultBackup = obj2.isDefaultBackup;
                    obj1.diff.hasChange = true;
                    obj1.diff.isDefaultBackup = obj2.isDefaultBackup;
                }
                if (obj1.isMainResource != obj2.isMainResource) {
                    obj1.isMainResource = obj2.isMainResource;
                    obj1.diff.hasChange = true;
                    obj1.diff.isMainResource = obj2.isMainResource;
                }

            }

            function registerResource(dataArr) {
                updateRecord(dataArr, recordResource)
            }

            function registerBackup(dataArr) {
                updateRecord(dataArr, recordBackup)
            }

            function updateRecord(dataArr, recordObj) {
                var tempmap = {};
                $.each(dataArr, function (i, element) {
                    tempmap["flash" + element.id] = element;
                })
                var removeKeyArr = [];
                for (var key in recordObj) {
                    if (tempmap.hasOwnProperty(key)) {
                        recordDiff(recordObj[key], tempmap[key]);
                        delete tempmap[key];
                    } else {
                        removeKeyArr.push(key);
                    }
                }
                $.each(removeKeyArr, function (i, removeKey) {
                    delete recordObj[removeKey];
                })

                doRemovePlayerView(removeKeyArr);
                for (var key in tempmap) {
                    recordObj[key] = tempmap[key];
                    recordObj[key].diff = {isNew: true, hasChange: true};
                }
                doDiffUpdatePlayerView(recordObj);
            }

            function doRemovePlayerView(removeKeyArr) {
                $.each(removeKeyArr, function (i, removeKey) {
                    removeKey = removeKey.replace(/flash/, "");
                    $("div[data-div-id=" + removeKey + "]").remove();
                    console.log("remove child " + removeKey);
                })

            }

            function doDiffUpdatePlayerView(recordObj) {
                for (var key in recordObj) {
                    if (recordObj[key].diff.hasChange == true) {
                        if (recordObj[key].diff.isNew == true) {
                            addPlayerView(recordObj[key])
                        } else {
                            updatePlayerView(recordObj[key])
                        }
                    }
                }
            }

            function addPlayerView(element) {
                var htmlArr = [];
                console.log("element" + JSON.stringify(element))
                if (element.isBackup == 1) {
                    htmlArr.push(Director.Util.makeUpBackUpDiv(element));
                    $("#backUpAddDiv").before(htmlArr.join(""));
                    initMicroPlayer(element)
                } else {
                    if (element.signalType == 0 || element.signalType == 2) {
                        htmlArr.push(Director.Util.makeUpResourceDiv(element));
                    } else {
                        htmlArr.push(Director.Util.makeUpResourceType1Div(element));
                    }
                    $("#resourceAddDiv").before(htmlArr.join(""));
                    initMicroPlayer(element)
                }

                if (element.isDefaultBackup == 1) {
                    $("div[data-div-id=" + element.id + "]").append(Director.Config.ImgLogo);
                }
                if (element.id == manager.newId) {
                    sendToFlash("flashPlayer" + element.id, {type: "changeRes",data: {resourceId:element.id}  } , true)
                }
                if (element.isMainResource) {
                    $("div[data-div-id=" + element.id + "]").append(Director.Config.ImgLogoMainResource);
                }
            }

            function updatePlayerView(element) {
                var elementDom = $("div[data-div-id=" + element.id + "]");
                if (element.diff.hasOwnProperty("signalName")) {
                    elementDom.find("input").val(element.diff.signalName)
                }
                if (element.diff.hasOwnProperty("isDefaultBackup")) {
                    if (element.diff.isDefaultBackup == 1) {
                        $("#imgLogo").appendTo(elementDom);
                    }
                }
                if (element.diff.hasOwnProperty("isMainResource")) {
                    if (element.diff.isMainResource) {
                        $("#imgLogo_mainResource").appendTo(elementDom);
                    }
                }
            }

            function setCurResourceId(resourceId) {
                if (resourceId == manager.newId) {
                    return;
                }
                manager.oldId = manager.newId;
                manager.newId = resourceId;
                console.log("  manager.oldId:"+  manager.oldId +"; manager.newId:"+manager.newId )
            }

                function notifyPlayingChange() {
                var elementDom = null;
                if (manager.oldId > 0) {
                    elementDom = $("div[data-div-id=" + manager.oldId + "]");
                    if (elementDom.length > 0) {
                        console.log("notifyPlayingChange close:" + manager.oldId);
                        sendToFlash("flashPlayer" + manager.oldId, {type: "changeRes", data: {resourceId:manager.newId}})
                    }
                }
                if (manager.newId > 0) {
                    elementDom = $("div[data-div-id=" + manager.newId + "]");
                    if (elementDom.length > 0) {
                        console.log("notifyPlayingChange start: " + manager.newId)
                        sendToFlash("flashPlayer" + manager.newId, {type: "changeRes",data: {resourceId:manager.newId}  })
                    }
                }
            }

            //搭建js与flash互通的环境
            function thisMovie(movieName) {
                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window[movieName];
                } else {
                    return document[movieName];
                }
            }

            function stopVol(flashId){
                sendToFlash(flashId,{type:"changeVoice",data:{value:0}})
            }
            function recoverVol(flashId){
                sendToFlash(flashId,{type:"changeVoice",data:{value:1}})
            }
//            function updatePreviewPlayer( streamUrl){
//                var flashvars = makeUpFlashvarsByStreamUrl(streamUrl )
//                sendToFlash("flv_preview",{type:"",data:flashvars},true)
//            }

            function addEffect(data) {
                openEditEffect();
                sendToFlash(effectFlashId, {type:"addEffect", data: data});
            }

            function openEditEffect() {
                sendToFlash(effectFlashId, {type: "openEdit"});
            }

            function closeEditEffect(mode) {  // mode: 1 或者 0  (1: 返回预览数据, 0: 不需要数据)
                sendToFlash(effectFlashId, {type: "closeEdit", data:mode});
            }

            function editEffect(data) {
                sendToFlash(effectFlashId, {type:"changeEffect", data: data});
            }

            function removeEffect(eid) {
                sendToFlash(effectFlashId, {type: "removeEffect", data: eid});
            }

            function checkFlash() {
                var flag = false;
                if(window.ActiveXObject){
                    try{
                        var swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
                        if(swf){
                            flag = true;
                        }
                    }catch(e){
                    }
                }else{
                    try{
                        var swf = navigator.plugins['Shockwave Flash'];
                        if(swf){
                            flag = true;
                        }
                    }catch(e){
                    }
                }

                if(flag){
                    console.log("flash running ok");
                }else{
                    console.log("flash running error");
                }

                return flag;
            }

            function noFlashTip(elementId) {
                var e = $("#" + elementId);
                if(!e) {
                    return;
                }

                e.html('<div class="need-flash"><p>您没有安装Flash播放器或者Flash播放器版本过低</p><p>请点击<a href="http://get.adobe.com/cn/flashplayer/">这里</a>安装</p><p class="grey">安装完毕之后请刷新页面或者重新启动浏览器</p></div>')
            }

            function changeFlash () {
                var mainResouceId = null;
                var entity = Director.Util.getEntity();
                var mainResourceId = entity.mainResourceId;
                entity.resourceId = mainResourceId;
                if (mainResourceId != null) {
                    setCurResourceId(mainResourceId);
                    notifyPlayingChange();
                }
            }

            return {
                initPlayer: initPlayer,
                notifyJS: notifyHandler,
                registerResource: registerResource,
                registerBackup: registerBackup,
                setCurResourceId: setCurResourceId,
                notifyPlayingChange: notifyPlayingChange,
                stopVol:stopVol,
                recoverVol:recoverVol,
                createPreview:createPreview,
                createFlvPreview:createFlvPreview,
                sendToFlash:sendToFlash,
                addEffect: addEffect,
                openEditEffect: openEditEffect,
                closeEditEffect: closeEditEffect,
                removeEffect: removeEffect,
                notifyHandler: notifyHandler,
                editEffect: editEffect,
                checkFlash: checkFlash
            }
        })()
    }
);